/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: MiPushReceiver.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.data_manager;

import android.app.ActivityManager;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageReceiver;

import java.util.List;

public class MiPushReceiver extends PushMessageReceiver {
    private String mRegId;
    private long mResultCode = -1;
    private String mReason;
    private String mCommand;
    private String mMessage;
    private String mTopic;
    private String mAlias;
    private String mUserAccount;
    private String mStartTime;
    private String mEndTime;

    public static void startMipush(Context context, String id, String key){
        final String TAG = "mipsuh";
        if(shouldInit(context)) {
            MiPushClient.registerPush(context, id, key);
        }
        //打开Log
        LoggerInterface newLogger = new LoggerInterface() {

            @Override
            public void setTag(String tag) {
                // ignore
            }

            @Override
            public void log(String content, Throwable t) {
                Log.d(TAG, content, t);
            }

            @Override
            public void log(String content) {
                Log.d(TAG, content);
            }
        };
        Logger.setLogger(context, newLogger);
    }

    public static void stopMipush(Context context){
        MiPushClient.unregisterPush(context);
    }

    private static boolean shouldInit(Context context) {
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        if (processInfos != null) {
            String mainProcessName = context.getPackageName();
            int myPid = android.os.Process.myPid();
            for (ActivityManager.RunningAppProcessInfo info : processInfos) {
                if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                    return true;
                }
            }
        }
        return false;
    }


    @Override
    public void onReceivePassThroughMessage(Context context, MiPushMessage message) {
        Log.w("MiPushReceiver", "onReceivePassThroughMessage");
        mMessage = message.getContent();

        /*if (!TextUtil.isEmpty(mMessage))
            MyPushManager.getInstance(context).loadMessage(mMessage);
        if(!TextUtils.isEmpty(message.getTopic())) {
            mTopic=message.getTopic();
        } else if(!TextUtils.isEmpty(message.getAlias())) {
            mAlias=message.getAlias();
        } else if(!TextUtils.isEmpty(message.getUserAccount())) {
            mUserAccount=message.getUserAccount();
        }

            MtcWakeLock.acquire(context, 180000L);
            context.startService(new Intent(context, MtcService.class));
            if(MtcCli.Mtc_CliGetState() == 2) {
                MtcCli.Mtc_CliRefresh();
            } else {
                String currentUser = MtcProvDb.Mtc_ProvDbGetCurProfUser();
                if(!TextUtils.isEmpty(currentUser)) {
                    int ret = MtcApi.login(currentUser, (JSONObject)null);
                    if(ret == 0) {
                        MtcUtil.Mtc_AnyLogInfoStr("Cloud sample2", "recv push and logining");
                    }
                }
            }
            */
    }
    @Override
    public void onNotificationMessageArrived(Context context, MiPushMessage message) {
        if(message == null)
            return;
        Log.w("===MiPushReceiver===", "onNotificationMessageArrived" + message.getContent());
        mMessage = message.getContent();
        //if (!TextUtil.isEmpty(mMessage))
        //MyPushManager.getInstance(context).loadMessage(mMessage);
        if(!TextUtils.isEmpty(message.getTopic())) {
            mTopic=message.getTopic();
        } else if(!TextUtils.isEmpty(message.getAlias())) {
            mAlias=message.getAlias();
        } else if(!TextUtils.isEmpty(message.getUserAccount())) {
            mUserAccount=message.getUserAccount();
        }
        /*
            MtcWakeLock.acquire(context, 180000L);
            context.startService(new Intent(context, MtcService.class));
            if(MtcCli.Mtc_CliGetState() == 2) {
                MtcCli.Mtc_CliRefresh();
            } else {
                String currentUser = MtcProvDb.Mtc_ProvDbGetCurProfUser();
                if(!TextUtils.isEmpty(currentUser)) {
                    int ret = MtcApi.login(currentUser, (JSONObject)null);
                    if(ret == 0) {
                        MtcUtil.Mtc_AnyLogInfoStr("Cloud sample2", "recv push and logining");
                    }
                }
            }*/
    }
    @Override
    public void onNotificationMessageClicked(Context context, MiPushMessage miPushMessage) {

        super.onNotificationMessageClicked(context, miPushMessage);
        if(miPushMessage == null)
            return;
        Log.w("onNotificationClicked", miPushMessage.getContent());
        mMessage = miPushMessage.getContent();
        //if (!TextUtil.isEmpty(mMessage))
        //    MyPushManager.getInstance(context).loadXiaomiNoticeMessage(mMessage);
    }

    /*public void onReceiveMessage(Context context, MiPushMessage message) {
        Log.w("----MiPushReceiver----","onReceiveMessage");
        if (!TextUtil.isEmpty(mMessage))
            MyPushManager.getInstance(context).loadMessage(mMessage);

            MtcWakeLock.acquire(context, 180000L);
            context.startService(new Intent(context, MtcService.class));
            if(MtcCli.Mtc_CliGetState() == 2) {
                MtcCli.Mtc_CliRefresh();
            } else {
                String currentUser = MtcProvDb.Mtc_ProvDbGetCurProfUser();
                if(!TextUtils.isEmpty(currentUser)) {
                    int ret = MtcApi.login(currentUser, (JSONObject)null);
                    if(ret == 0) {
                        MtcUtil.Mtc_AnyLogInfoStr("Cloud sample2", "recv push and logining");
                    }
                }
            }

    }*/

    @Override
    public void onCommandResult(Context context, MiPushCommandMessage message) {
        String command = message.getCommand();
        Log.w("----onCommandResult----", message.getCommandArguments().toString());
        if("register".equals(command) && message.getResultCode() == 0L) {
            List arguments = message.getCommandArguments();
            String regId = arguments != null && arguments.size() > 0?(String)arguments.get(0):null;
            if(!TextUtils.isEmpty(regId)) {
                //MiPush.register(context, regId);
                //MyPushManager.getInstance(context).setPushToken(regId, MyPushManager.PUSH_XIAOMI);
            }
        }

    }

}

